package com.example.forum.controller;

import com.example.forum.entity.User;
import com.example.forum.exception.CustomException;
import com.example.forum.result.Result;
import com.example.forum.services.impl.ArticleReplyServiceImpl;
import com.example.forum.vo.ArticleReplyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.forum.constant.MessageConstant.USER_MUTED;
import static com.example.forum.constant.MessageConstant.USER_SESSION;

@Slf4j
@Tag(name = "回复接口")
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Autowired
    private ArticleReplyServiceImpl articleReplyService;

    /**
     * 回复文章
     *
     * @param request
     * @param id
     * @param content
     * @return
     */
    @Operation(summary = "回复文章")
    @PostMapping("/create")
    public Result create(HttpServletRequest request,
                         @Parameter(description = "回复id") @RequestParam(value = "articleId") @NotNull Long id,
                         @Parameter(description = "回复内容") @RequestParam(value = "content") @NotNull String content) {
        // 获取用户信息
        User user = (User) request.getSession(false).getAttribute(USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            return Result.error(USER_MUTED);
        }
        try {
            // 回帖
            articleReplyService.create(id, content, user);
            return Result.success();
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取回复列表
     *
     * @param articleId
     * @return
     */
    @Operation(summary = "获取回复列表")
    @GetMapping("/getReplies")
    public Result<List<ArticleReplyVO>> getReplyList(@Parameter(description = "文章id") @RequestParam(value = "articleId") @NotNull Long articleId) {
        try {
            List<ArticleReplyVO> list = articleReplyService.getReplyList(articleId);
            return Result.success(list);
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
